var largestSumAfterKNegations = function(nums, k) {
    let res = 0;
    nums.sort((a,b) => a-b);
    if(nums[0]>=0) {
        if(k%2!==0) {
            nums[0] = -nums[0]
        }
        res = nums.reduce((pre,item) => pre+item)
        return res;
    }
    for(let i = 0; i < k;i++) {
        if(nums[i]==0) {
            break;
        }
        else if (nums[i]<0){
            nums[i] = -nums[i];
        }
        else {
            console.log(nums,'122')
            let min = Math.min.apply(null,nums)
            console.log(min,'123')
            let n = nums.findIndex(item =>item==min)
            console.log(n)
            nums[n] = -nums[n]
        }
    }
    res = nums.reduce((pre,item) => pre+item)
    return res;
};
console.log(largestSumAfterKNegations([-8,3,-5,-3,-5,-2],6))
console.log(largestSumAfterKNegations([5,6,9,-3,3],2))

// 官方题解
var largestSumAfterKNegations = function(nums, k) {
    nums.sort((a, b) => {
        return Math.abs(b) - Math.abs(a)
    })
    for(let i = 0; i < nums.length; i++) {
        if(nums[i] < 0 && k > 0) {
            nums[i] *= -1
            k--
        }
    }

    if(k > 0 && k % 2 === 1) {
        nums[nums.length - 1] *= -1   
    }
    k = 0

    return nums.reduce((a, b) => {
        return a + b
    })
};